import axios from 'axios'
import {MessageBox, Message, Loading} from 'element-ui'
import store from '../store'
import errorCode from '../const/errorCode'
import {Toast} from 'vant';
import {getToken} from '@/utils/auth'
import Cookies from "js-cookie";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
    baseURL: 'https://debug.yasee.com.cn', //测试环境地址
    // baseURL: 'https://wechat.yasee.com.cn', //生产环境地址
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 35000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        // if (getToken()) {
        // let each request carry token
        // please modify it according to the actual situation
        // config.headers['Authorization'] = 'Bearer ' + getToken()
        // config.headers["Authorization"] = "Bearer " + sessionStorage.getItem('token')
        // config.headers['Authorization'] = 'Bearer ' + '4659cfba-fc35-42dd-b000-53e92dfcd9fb'
        // }
        if (!config.headers.Authorization) {
            config.headers["Authorization"] = 'Bearer ' + Cookies.get('token') //管理员
        }
        return config
    },
    error => {
        // do something with request error
        // console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (res) => {
        const status = Number(res.status) || 200
        const message = res.data.msg || errorCode[status] || errorCode['default']
        // 后台定义 424 针对令牌过去的特殊响应码
        if (status === 424) {
            MessageBox.confirm('令牌状态已过期，请点击重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            )
                .then(() => {
                    // store.dispatch('LogOut').then(() => {
                    //     // 刷新登录页面，避免多次弹框
                    //     window.location.reload()
                    // })
                }).catch(() => {
            })
            return
        }

        if (status !== 200) {
            Message({
                message: message,
                type: 'error'
            })
            return Promise.reject(new Error(message))
        }

        return res.data
    },
    error => {
        if (error.response.status === 500) {
            Toast.fail(`${error.response.data.msg}`)
        }
        // 处理 503 网络异常
        if (error.response.status === 503) {
            Toast.fail(`${error.response.data.msg}`)
        }
        // NProgress.done() 进度条
        console.log(error.response)
        return Promise.reject(new Error(error))
    }
)

export default service
